package com.studyyoun.android.nonghe.welcom;

import android.content.Intent;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.studyyoun.android.androidcommonbaselibrary.activity.CommonBaseActivity;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.home.activity.HomeActivity;

public class WelcomActivity extends CommonBaseActivity {


    private WebView mWebView;
    private FrameLayout mRootViewLayout;
    private TextView mToMainPageTextView;

    @Override
    protected void getAllIntentExtraDatas(Intent intent) {

    }

    @Override
    protected int getCommonLayoutId() {
        return R.layout.activity_welcom_layout;
    }

    @Override
    protected void commonInitView(View view) {

        mWebView = findViewById(R.id.wb_welcome);
        mRootViewLayout = findViewById(R.id.ll_welcome_root_view);
        mRootViewLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        mToMainPageTextView = findViewById(R.id.tv_to_main);
        initWebViewSettings(mWebView);

    }

    @Override
    protected void commonFunction() {

    }

    private int mCount = 30;
    private int mNumber = 3;

    @Override
    protected void commonDelayFunction() {
        mWebView.loadUrl("http://u5288404.viewer.maka.im/k/FYA7RO5Q");

        mToMainPageTextView.setText("跳过 》》》");
        mHandler.postDelayed(mRunnable, 500);

        mToMainPageTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mHandler.removeCallbacksAndMessages(0);
                WelcomActivity.this.startActivity(new Intent(WelcomActivity.this, HomeActivity.class));
                WelcomActivity.this.finish();
            }
        });
    }


    private Runnable mTimeRunnable = new Runnable() {
        @Override
        public void run() {
            mCount--;
            mToMainPageTextView.setText("跳过(" + mCount + "s)");
            if (mCount != 0) {
                mHandler.postDelayed(mTimeRunnable, 1000);
            } else {
                WelcomActivity.this.startActivity(new Intent(WelcomActivity.this, HomeActivity.class));
                WelcomActivity.this.finish();
            }
        }
    };

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mNumber++;
            if (mNumber > 3) {
                mNumber = 0;
            }
            if (mNumber == 0) {
                mToMainPageTextView.setText("跳过 ");
            } else if (mNumber == 1) {
                mToMainPageTextView.setText("跳过 》");
            } else if (mNumber == 2) {
                mToMainPageTextView.setText("跳过 》》");
            } else if (mNumber == 3) {
                mToMainPageTextView.setText("跳过 》》》");
            }

            mHandler.postDelayed(mRunnable,500);
        }
    };

    private static final String APP_CACAHE_DIRNAME = "/wisdom/webcache";

    private void initWebViewSettings(WebView webView) {
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //支持插件
        webSettings.setPluginState(WebSettings.PluginState.ON);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(false); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //设置缓冲大小，我设的是8M
        webSettings.setAppCacheMaxSize(1024 * 1024 * 105);

        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式

        // 开启 DOM storage API 功能

        webSettings.setDomStorageEnabled(true);


        //开启 database storage API 功能

        webSettings.setDatabaseEnabled(true);

        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;

//      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;


        //设置数据库缓存路径

        webSettings.setDatabasePath(cacheDirPath);

        //设置  Application Caches 缓存目录

        webSettings.setAppCachePath(cacheDirPath);

        //开启 Application Caches 功能

        webSettings.setAppCacheEnabled(true);

        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setBlockNetworkImage(false);
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mDensity = metrics.densityDpi;


        /**
         *用WebView显示图片，可使用这个参数 设置网页布局类型：1、LayoutAlgorithm.NARROW_COLUMNS ：
         *适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
         */
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        mWebView.setWebViewClient(new CustomWebViewClient());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mWebView.destroy();
        mRootViewLayout.removeAllViews();
    }

    private class CustomWebViewClient extends WebViewClient {
        private View mErrorView;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            mHandler.removeCallbacksAndMessages(0);
//            WelcomActivity.this.startActivity(new Intent(WelcomActivity.this, HomeActivity.class));
//            WelcomActivity.this.finish();
            return true;
        }
    }
}
